﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Hasiu.Mvc.Controllers.Tools
{
    public class UploadToolsController : Controller
    {
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase filedata)
        {
            try
            {
                Response.Expires = -1;
                var fileName = filedata.FileName;
                var extension = Path.GetExtension(fileName).ToLower();
                const string tempPath = "~/temp/";
                if (!Directory.Exists(Server.MapPath(tempPath)))
                    Directory.CreateDirectory(Server.MapPath(tempPath));
                var filename = Guid.NewGuid().ToString("N") + extension;
                filedata.SaveAs(Server.MapPath(tempPath + filename));
                Response.Write(tempPath.Substring(1) + filename);
                Response.StatusCode = 200;
            }
            catch
            {
            }
            return new EmptyResult();
        }

        [HttpPost]
        public ActionResult UploadImg(HttpPostedFileBase filedata, string p)
        {
            try
            {
                Response.Expires = -1;
                var extension = Path.GetExtension(filedata.FileName).ToLower();
                if (extension != ".jpg" &&
                    extension != ".jpeg" &&
                    extension != ".gif" &&
                    extension != ".png" &&
                    extension != ".bmp")
                {
                    return new EmptyResult();
                }
                var tempPath = "~/temp/";
                if (p == "edit")
                {
                    tempPath = "~/file/";
                }
                if (!Directory.Exists(Server.MapPath(tempPath)))
                    Directory.CreateDirectory(Server.MapPath(tempPath));
                var filename = Guid.NewGuid().ToString("N") + extension;
                filedata.SaveAs(Server.MapPath(tempPath + filename));
                Response.Write(tempPath.Substring(1) + filename);
                Response.StatusCode = 200;
            }
            catch
            {
            }
            return new EmptyResult();
        }
    }
}